#include "LinkedList.h"

void LinkedList::Add(ElemType data) //增加新结点
{
    Lnode *newNode = new Lnode(data); // new一个Lnode类型指针并将data存入里面
    if (head->next == nullptr)        //链表为空时
        head->next = newNode;
    else //链表不为空时
    {
        Lnode *temp = head->next;
        while (temp->next != nullptr) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
    size++;
}
void LinkedList::Delete(int i) //删除第i个结点
{
    if (i >= 1 && i <= size) {
        Lnode *p = head;
        for (int j = 1; j < i; j++) {
            p = p->next;
        }
        Lnode *q = p->next;
        p->next = q->next;
        delete q;
    } else
        cout << "不存在第" << i << "个结点" << endl;
}
Lnode *LinkedList::Find(ElemType e) //按值查找，查找是否存在该结点。如果存在，则返回其地址
{
    Lnode *p = head;
    if (p != nullptr) {
        for (int i = 1; i <= size; i++) {
            p = p->next;
            if (p->Data == e) {
                cout << "存在" << endl;
                return p;
            }
        }
        cout << "不存在" << endl;
        return nullptr;
    }
    cout << "链表为空" << endl;
    return nullptr;
}
void LinkedList::Modify(int i, ElemType e) //修改第i个结点的内容
{
    if (i >= 1 && i <= size) {
        Lnode *p = head;
        for (int j = 1; j <= i; j++) {
            p = p->next;
        }
        p->Data = e;
    } else
        cout << "不存在第" << i << "个结点" << endl;
}
void LinkedList::Insert(int i, ElemType e) //插入（在第i个结点前插入新结点）
{
    if (i >= 1 && i <= size) {
        Lnode *E = new Lnode(e);
        Lnode *p = head;
        for (int j = 1; j < i; j++) {
            p = p->next;
        }
        E->next = p->next;
        p->next = E;
    } else
        cout << "插入位置不合理" << endl;
}
void LinkedList::GetNode(int i, ElemType &e) //获取第i个结点的内容
{                                            // i必须大于等于1
    Lnode *p = head;
    if (p != nullptr) {
        for (int j = 1; j <= i; j++) {
            p = p->next;
        }
        e = p->Data;
        return;
    } else
        cout << "链表为空" << endl;
}
bool LinkedList::IsNull(LinkedList &L) //判断链表是否为空
{
    if (L.head != nullptr)
        return false;
    else
        return true;
}
int LinkedList::ListLength() //获取链表长度
{
    return size;
}
void LinkedList::Clear() //清空链表
{
    Lnode *p, *q;
    p = head->next;
    while (p) // p为空则停止
    {
        q = p->next;
        delete p;
        p = q;
    }
    head->next = nullptr;
}
LinkedList::~LinkedList() //销毁链表
{
    Lnode *p;
    while (head) // head为空则停止
    {
        p = head;
        head = head->next;
        delete p;
    }
}